<template>
	<div class="resource-detail maxW" v-loading="loading" element-loading-background="rgba(255, 255, 255, 1)">
		<div class="resource-nav-link">
			<router-link to="/home/resourceList">教学资源</router-link>
			<strong>
				<i>></i>
				{{ resourceData.name }}.{{ resourceData.postfix }}
			</strong>
		</div>
		<div class="resource-content clear">
			<div class="resource-content-l fl">
				<div class="resource-content-top clear">
					<img v-if='resourceData.file_type' :src="hostURL + '/static/index/images/format/resourceicon' + resourceData.file_type + '.png'" class="resource-icon" />
					<div class="resource-con-info">
						<div class="resource-box-l fl">
							<h2 class="resource-title" v-if="resourceData.name">{{ resourceData.name }}.{{ resourceData.postfix }}</h2>
							<div class="create-info">
								<span class="creater-name">{{ resourceData.u_name }}</span>
								<em>
									上传于
									<i class="create-time">{{ resourceData.create_time }}</i>
								</em>
								<em>
									大小：
									<i class="file-size">{{ filesize }}</i>
								</em>
								<em>
									评分
									<strong>
										<i class="score">{{ resourceData.scores }}</i>
									</strong>
								</em>
							</div>
						</div>
						<el-button type="primary" class="download-btn fr" @click="downloadFile()">下载</el-button>
					</div>
				</div>
				<div class="resource-content-mid">
					<ul class="clear">
						<li>
							<i class="ipng icon_see"></i>
							<em class="clicks">{{ resourceData.clicks == 0 ? '1' : resourceData.clicks }}点击</em>
						</li>
						<li>
							<i class="ipng Collection07"></i>
							<em class="favourite">{{ resourceData.f_count }}收藏</em>
						</li>
						<li>
							<i class="ipng download01"></i>
							<em class="downloads">{{ resourceData.downloads }}下载</em>
						</li>
					</ul>
				</div>
				<div class="resource-content-bottom">
					<template v-if="viewData.file_type == 3">
						<img :src="hostURL + viewData.src" alt="图片" style="width:100%;height:100%" />
					</template>
					<template v-else-if="viewData.file_type == 1">
						<iframe :src="hostURL + viewData.url" style="width:100%;height:500px"></iframe>
					</template>
					<template v-else-if="viewData.file_type == 2">
						<div class="common-box">viewData.content</div>
					</template>
					<template v-else-if="viewData.file_type == 5">
						<div class="common-box" >
							<VueAudio  :audio-content="audioContent"  ref="audioContent" /> 
						</div>
						
					</template>
					<template v-else-if="viewData.file_type == 6">
						<!-- <nativeVideo :playParam.sync="playParam" v-if="viewData.transform_status==1"></nativeVideo> -->
						<dplayerA :playParam.sync="playParam" v-if="viewData.transform_status==1"></dplayerA>
                        <div v-else class="transform-loading">
                                视频正在转码中，稍等片刻刷新页面观看...
                        </div>
					</template>
					<div class="empty-bgc-img" v-if="pleaceholder == true">
						<div class="resource-mask">
							<span>{{ tipWords }}</span>
						</div>
					</div>
				</div>
				<div class="resource-content-tool clear">
					<div class="mark fl">
						<span>评分</span>
						<el-rate v-if="isMark == false" :allow-half="true" :max="5" v-model="score" @change="addMark"></el-rate>
						<el-rate v-else :value="score / 2" :allow-half="true" :max="5" disabled></el-rate>
					</div>
					<div class="collect-share fr clear">
						<share :wapPath='wapPath'></share>
					</div>
					<div class="resource-collect fr">
						<span class="a-tit" v-html="isCollect? '已收藏' : '收藏'"></span>
						<i :class="[isCollect? 'ipng collect' : 'ipng uncollect']" title="点击收藏或取消收藏" @click="collectResource"></i>
						<i class="line"></i>
					</div>
				</div>
			</div>

			<div class="resource-content-r fr">
				<div class="resource-info-title clear">
					<span class="words fl">同类推荐</span>
					<el-button class="fr" type="text" @click="changeList">换一批</el-button>
				</div>
				<ul>
					<li class="resource-info-li clear" v-for="(item, index) of similarResourceData" :key="index">
						<!-- <router-link :to="{path: '/home/resourceDetail', query: { id: item.id }}"> -->
                        <a href="javascript:;" @click="gotoDetail(item.id)">
							<span class="file-img fl"><img :src="hostURL + '/static/index/images/format/resourceicon' + item.file_type + '.png'" /></span>
							<div class="file-text">
								<p class="file-name">{{ item.name }}.{{ item.postfix }}</p>
								<div class="file-info">
									<span class="download-count">下载：{{ item.downloads }}</span>
									<span class="section-info">
										{{ item.uo_study_section_name == null ? '暂无学段' : item.uo_study_section_name }} :{{
											item.uo_grade_name == null ? '暂无年级' : item.uo_grade_name
										}}
									</span>
								</div>
							</div>
                        </a>
						<!-- </router-link> -->
					</li>
				</ul>
			</div>
		</div>
	</div>
</template>
<script>
import VueAudio from '../../common/audio-player';
import nativeVideo from '../../common/nativeVideo';
import share from '../../common/share';
import dplayerA from '../../common/dplayerA';
import { fail } from 'assert';
export default {
	components: {
		// nativeVideo,
		dplayerA,
		VueAudio,
        share
    },
    props: {
        userData:{}
	},
	data() {
		return {
			loading:true,
			hostURL: '',
			resourceId: this.$route.query.id,
			resourceData: {}, // 资源数据
			filesize: '', //文件大小(带单位)
			score: 0, // 评分
			isMark: false, //是否已经评分
			isCollect: false, //是否已经收藏
			allowLoad: 1, //1允许下载，0不允许
			sectionId: null, //同类学段id
			gradeId: null, //同类年级id
			similarResourceData: [], //同类资源数组
			pleaceholder: false, //资源预览没数据的占位符
			tipWords: '', //资源预览提示语
			viewData: {}, //预览的数据
			playParam: { play_url: '' }, //视频预览
			audioContent: {/*音频预览*/
			    url: '',
			    name: '',
			    title: '试听',
			},
		};
	},
	created() {
		this.getResource();
		this.hostURL = sessionStorage.getItem('host_addr');
		this.getViewURL();
	},
	computed: {
		wapPath(){
			const Code = sessionStorage.getItem('CheckSchoolAppCode')  
            return `${window.location.origin}/wap/home?path=subjectDetails&bdShare=true&id=${this.resourceId}&CheckSchoolAppCode=${Code}`;
		},	 
	},  
	destroyed () {
		this.addClickCount(this.resourceData.clicks);
	},
	methods: {
        gotoDetail(_id) {
            window.open(`/home/resourceDetail?id=${_id}`, '_blank')
        },
		// 根据资源id获取资源
		getResource(type) {
			let success = res => {
				// console.log(res.data);
				if (res.data.length != 0) {
					this.resourceData = res.data[0];
					// 转换一下文件大小：
					let size = res.data[0].filesize / 1024 / 1024;
					if (Math.floor(size) != 0) {
						this.filesize = Math.floor(size) + 'mb';
					} else {
						this.filesize = Math.floor(size * 1024) + 'kb';
					}
					// 判断当前这个资源是否已经收藏
					this.isCollect = res.data[0].f_id == null ? false : true;
					// 判断是否已对资源进行评分
					if (res.data[0].f_co_score == null) {
						this.isMark = false;
					} else {
						this.score = res.data[0].f_co_score;
						this.isMark = true;
					}
					//是否允许下载
					this.allowLoad = res.data[0].is_download;

					// 获取学段、年级的id
					this.sectionId = res.data[0].study_section_id;
					this.gradeId = res.data[0].grade_id;
					// console.log(res.data[0].clicks)
					if (type != 'collect') {
						//获取 同类推荐 列表的数据
						this.getSimilarResource(res.data[0].study_section_id, res.data[0].grade_id);
					}
					this.loading = false;
				} else {
					this.$message.warning('该资源已被删除~');
					this.$router.push('/home/resourceList');
					this.loading = false;
				}
			};
            let fail = res =>{
                this.$message.warning('该资源已被删除~');
                this.$router.push('/home/resourceList');
            }
			this.$ajax({
				url: 'api/resource/resource',
				method: 'get',
				params: {
					id: this.resourceId,
					userid: this.userData.userInfo.id?this.userData.userInfo.id:0
				},
				func: {
					success: success,
					fail: fail
				}
			});
		},
		// 修改点击次数
		addClickCount(clicks) {
			if(!isNaN(clicks)){
				let success = data => {};
				this.$ajax({
					url: 'api/resource/resource',
					method: 'put',
					data: {
						id: this.resourceId,
						clicks: clicks === 0 ? 2 : clicks + 1
					},
					func: {
						success: success
					}
				});
			}
		},
		// 添加评分
		addMark() {
			//如果已评分了，就不能再评
			if (this.isMark == true) {
				return;
			}
			if (this.userData.userInfo.id===0) {
				this.$message.warning('请先登录');
				return;
			}
			let success = data => {
				this.$message.success('评分成功');
				this.getResource();
			};
			this.$ajax({
				url: 'api/comment/comment',
				method: 'post',
				data: {
					res_id: this.resourceId,
					user_id: this.userData.userInfo.id,
					origin: 1,
					score: this.score * 2
				},
				func: {
					success: success
				}
			});
		},
		//收藏资源：
		collectResource() {
			if (this.userData.userInfo.id===0) {
				this.$message.warning('请先登录');
				return;
			}
			let success = data => {
				if (!this.isCollect) {
					this.$message.success('收藏成功');
				} else {
					this.$message.success('已取消收藏');
				}
				this.getResource('collect');
			};
			if (!this.isCollect) {
				this.$ajax({
					url: 'api/favourite/favourite',
					method: 'post',
					data: {
						res_id: this.resourceId,
						user_id: this.userData.userInfo.id,
						origin: 1
					},
					func: {
						success: success
					}
				});
			} else {
				this.$ajax({
					url: 'api/favourite/favourite',
					method: 'delete',
					params: {
						res_id: this.resourceId,
						user_id: this.userData.userInfo.id,
						origin: 1
					},
					func: {
						success: success
					}
				});
			}
		},
		// 下载：
		downloadFile() {
			if (this.allowLoad == 0) {
				this.$message.warning('该资源创建者不允许下载');
			} else {
                if (this.userData.userInfo.id===0) {
                    this.$message.warning('先登陆个人账号，才能进行此操作哦~');
                    return;
                }
				window.location.href = this.hostURL + '/index/resource/resourcedownload?id=' + this.resourceId;
				this.addDownCounts();
			}
		},
		// 添加下载次数,type（1 资源    0 视频）
		addDownCounts() {
			let success = data => {
				this.getResource();
			};
			this.$ajax({
				url: 'index/resource/add_download_nums',
				method: 'post',
				data: {
					id: this.resourceId,
					userid: this.userData.userInfo.id,
					type: 1
				},
				func: {
					success: success
				}
			});
		},
		// 获取同类资源
		getSimilarResource(sectionId, gradeId) {
            const array=['id','create_time','clicks','downloads']
			let orderby = array[parseInt(4 * Math.random())];
			let success = data => {
				this.similarResourceData = data.data.rows;
			};
			this.$ajax({
				url: 'api/resource/resource',
				method: 'get',
				params: {
					data_type: 1,
					grade_id: gradeId,
					orderby: orderby,
					page: 1,
					size: 6,
					study_section_id: sectionId,
					not_in_file_type: 2,
					status: 1,
					authonity: 1
				},
				func: {
					success: success
				}
			});
		},
		// 换一批
		changeList() {
			this.getSimilarResource(this.sectionId, this.gradeId);
		},
		//获取资源预览的地址
		getViewURL() {
			let success = res => {
				if (is_empty(res.data)) {
					this.pleaceholder = true;
					this.tipWords = '该资源不支持预览';
				} else {
					if (res.data.code == 404) {
						this.pleaceholder = true;
						this.tipWords = '该资源正在转码中';
					} else {
						this.viewData = res.data;
						if (res.data.file_type == 6) {
							//视频rtmp流
							this.playParam.play_url = res.data.rtmpurl;
						}
						if (res.data.file_type == 5) {
							//音频
							this.audioContent.url = this.hostURL + res.data.mp3url;
						}
					}
				}
			};
			this.$ajax({
				url: 'api/resource/resource_view',
				method: 'get',
				params: {
					id: this.resourceId
				},
				func: {
					success: success
				}
			});
		}
	}
};
</script>

<style lang="scss">

.resource-nav-link {
	padding: 24px 0;
	font-size: 16px;

	a {
		color: #333;
	}

	i {
		margin: 0 6px;
	}

	strong {
		color: #999;
	}
}
.resource-content {
	padding-bottom: 40px;
}
.resource-content-l {
	display: inline-block;
	width: 70%;
	background-color: #fff;
	padding: 20px 30px;
	.resource-box-top {
		margin-bottom: 40px;
	}

	.resource-icon {
		max-width: 42px;
		max-height: 52px;
		overflow: hidden;
		float: left;
	}

	.resource-con-info {
		margin-left: 75px;
	}

	.resource-box-l {
		.resource-title {
			font-size: 18px;
			line-height: 20px;
			max-width: 500px;
		}

		.create-info {
			font-size: 12px;
			line-height: 16px;
			color: #888888;
			margin-top: 15px;
		}

		.creater-name {
			color: #020202;
			margin-right: 20px;
		}

		em {
			padding-right: 15px;
		}

		.score {
			font-size: 18px;
			color: #f7a303;
			margin-left: 15px;
		}
	}

	.download-btn {
		padding: 0;
		width: 90px;
		height: 35px;
	}

	.resource-content-mid {
		margin: 40px 0;

		li {
			display: block;
			float: left;
			text-align: center;
			margin-right: 80px;
		}

		em {
			color: #666666;
			line-height: 16px;
			margin-top: 10px;
			display: block;
		}
	}

	.resource-content-bottom {
		height: 500px;
		line-height: 500px;
		>img{
			object-fit: contain;
		}
		.empty-bgc-img {
			display: inline-block;
			width: 100%;
			height: 500px;
			background-image: url('../../../../public/images/image08.png');
			background-size: 100% 100%;
			position: relative;
			.resource-mask {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.1);
				text-align: center;
				visibility: hidden;
				opacity: 0;
				-moz-transition: all 0.35s ease-in;
				-webkit-transition: all 0.35s ease-in;
				-o-transition: all 0.35s ease-in;
				transition: all 0.35s ease-in;
			}
			&:hover .resource-mask {
				visibility: visible;
				opacity: 1;
			}
			span {
				font-size: 24px;
				color: #ffffff;
				background: rgba(0, 0, 0, 0.1);
				border-radius: 15px;
				height: 70px;
				line-height: 70px;
				display: block;
				width: 370px;
				text-align: center;
				position: absolute;
				top: 45%;
				left: 50%;
				margin-left: -170px;
			}
		}
		.common-box {
			height: 100%;
			text-align: center;
			background-color: #a9cbe3;
			display: flex;
			align-items: center;
        }
        .transform-loading{
            display: flex;
            justify-content: center;
            font-size: 20px;
            color: #fff;
            background-color: #a9cbe3;
        }
	}

	.resource-content-tool {
		margin: 40px 0 20px;
		.mark {
			span,
			.el-rate {
				vertical-align: middle;
				font-size: 14px;
			}

			.el-rate {
				display: inline;
				margin-left: 10px;
			}
		}

		.collect-share {
            padding-top: 3px;
			.a-tit {
				font-size: 14px;
				height: 28px;
				line-height: 28px;
				margin-right: 10px;
			}
		}

		.resource-collect {
			height: 28px;
			line-height: 28px;
			padding-right: 15px;
			font-size: 14px;

			.ipng {
				width: 25px;
				height: 28px;
				cursor: pointer;
				margin-left: 5px;
			}

			.collect {
				background-position: -465px -774px;
			}

			.uncollect {
				background-position: -440px -774px;
			}

			.line {
				border-right: 1px solid #b1bdc2;
				padding-left: 20px;
			}
		}
	}
}

.resource-content-r {
	display: inline-block;
	width: 22%;
	background-color: #fff;
	padding: 5px 10px;
	box-sizing: border-box;
    min-height: 828px;
	.resource-info-title {
		padding-bottom: 15px;

		.words {
			font-size: 14px;
			color: #666;
			line-height: 40px;
		}

		.words,
		.el-button {
			vertical-align: middle;
		}
	}

	.resource-info-li {
		margin-bottom: 30px;
		cursor: pointer;
		.file-img {
			display: block;
			max-width: 42px;
			max-height: 52px;
			overflow: hidden;

			img {
				display: inline-block;
				width: 100px;
				vertical-align: top;
			}
		}

		.file-text {
			margin-left: 50px;
			font-size: 12px;
			line-height: 16px;
		}

		.file-name {
			height: 16px;
			overflow: hidden;
			word-wrap: break-word;
			word-break: break-all;
		}

		.file-info {
			margin-top: 8px;
		}

		.download-count {
			margin-right: 10px;
			color: #666;
		}

		.section-info {
			color: #666;
		}
	}
}
</style>
